package com.example.wto.viewpagertest01;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ParseLessonHtml implements ParseHtml
{
    private CollegeBean collegeBean = null;
    private String college_url;
    private Map<String, LessonBean> lessonMap = new HashMap<String, LessonBean>();
    private Map<String, TermBean> termMap = new HashMap<String, TermBean>();
    private String cookie;
    public static int CODE_ERROR;

    public ParseLessonHtml(CollegeBean collegeBean)
    {
        super();
        this.collegeBean = collegeBean;
        college_url = collegeBean.getCollege_url();
    }

    public Lesson getLesson(String tid, String teaid, String code)
    {
        Map<Integer, List<Course>> cmap = sendPost(tid, teaid, code);

        int j = 0;
        LessonBean bean = new LessonBean(collegeBean.getCollege_id(), collegeBean.getCollege_name
                (), tid, termMap.get(tid).getTermName(), teaid, lessonMap.get(teaid).getLessonName
				());
        Lesson lesson = new Lesson(bean);
        lesson.getWeekList().clear();
        if (cmap != null)
        {
            for (Map.Entry<Integer, List<Course>> l : cmap.entrySet())
            {
                System.out.println(WEEK[j]);
                System.out.println(l);
                if (j >= 7)
                {
                    break;
                }


                DayOfWeek weekDay = new DayOfWeek(WEEK[j]);
                weekDay.setCourseList(l.getValue());
                lesson.getWeekList().add(weekDay);
                j++;
            }

            return lesson;
        } else
        {
            return null;
        }
    }

    @Override
    public List getIndex()
    {
        try
        {
            URL url = new URL(college_url + "/ZNPK/KBFB_LessonSel.aspx");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            Map<String, List<String>> map = conn.getHeaderFields();
            cookie = map.get("Set-Cookie").get(0);
            System.out.println(cookie);
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "gbk"));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                builder.append(line);
            }
            String index = builder.toString();
            reader.close();
            conn.disconnect();

            Document doc = Jsoup.parse(index);
            Elements elements = doc.select("select[name=\"Sel_XNXQ\"] option");
            List<TermBean> termList = new ArrayList<TermBean>();
            if (termMap != null)
            {
                termMap.clear();
            }
            for (Element element : elements)
            {
                String t = " {\"id\":" + element.val() + ",\"name\":" + element.html() + "}";
                TermBean termBean = new TermBean(element.val(), element.html());
                termList.add(termBean);
                termMap.put(element.val(), termBean);
                System.out.println(t);
            }

            return termList;

        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;


    }

    @Override
    public int getImage()
    {
        HttpURLConnection conn = null;
        InputStream in = null;
        FileOutputStream fo = null;
        try
        {
            URL url = new URL(college_url + "/sys/ValidateCode.aspx");
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            conn.setRequestProperty("Referer", college_url + "/ZNPK/KBFB_LessonSel.aspx");
            in = conn.getInputStream();
            String imgPath = Environment.getExternalStorageDirectory() + File.separator +
                    "codeImage.jpg";
            File file=new File(imgPath);
            if (!file.exists())
            {
                file.createNewFile();
            }
            fo = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int length = 0;
            while ((length = in.read(buf, 0, buf.length)) != -1)
            {
                fo.write(buf, 0, length);
            }
            return 1;


        } catch (Exception e)
        {

            e.printStackTrace();
        } finally
        {
            try
            {
                in.close();
                fo.close();
                conn.disconnect();
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
        return -1;
    }

    // �������� ��ѧ�� �γ�id ��֤�뷢�͹�ȥ
    private Map<Integer, List<Course>> sendPost(String termId, String tid, String code)
    {
        try
        {
            URL url = new URL(college_url + "/ZNPK/KBFB_LessonSel_rpt.aspx");
            String param = "Sel_XNXQ=" + termId + "&Sel_KC=" + tid + "&gs=" + 1 + "&txt_yzm=" +
					code;
            // Connection con =
            // Jsoup.connect("http://jw.zzti.edu.cn/ZNPK/TeacherKBFB_rpt.aspx");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            conn.setRequestProperty("Accept",
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " +
							"Chrome/54.0.2840.87 Safari/537.36");
            conn.setRequestProperty("Upgrade-Insecure-Requests", "1");
            conn.setRequestProperty("Referer", college_url + "/ZNPK/KBFB_LessonSel.aspx");
            conn.setRequestProperty("Cache-Control", "max-age=0");

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(param);
            dos.flush();
            dos.close();

            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "gbk"));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                builder.append(line);
            }
            String info = builder.toString();
            if (info.contains("验证码错误"))
            {
                CODE_ERROR = 1;
                return null;
            }
            Document doc = Jsoup.parse(info);
            Elements elements = doc.select("td");
            elements.get(0);

            Map<Integer, List<Course>> cmap = new LinkedHashMap<>();

            List<Course> cl1 = new ArrayList<Course>();
            List<Course> cl2 = new ArrayList<Course>();
            List<Course> cl3 = new ArrayList<Course>();
            List<Course> cl4 = new ArrayList<Course>();
            List<Course> cl5 = new ArrayList<Course>();
            List<Course> cl6 = new ArrayList<Course>();
            List<Course> cl7 = new ArrayList<Course>();

            cmap.put(1, cl1);
            cmap.put(2, cl2);
            cmap.put(3, cl3);
            cmap.put(4, cl4);
            cmap.put(5, cl5);
            cmap.put(6, cl6);
            cmap.put(7, cl7);

            for (Element week : elements)
            {
                if (week.html().equals(WEEK[0]))
                {
                    Element wtr = week.parent();
                    Elements trs = wtr.siblingElements();
                    for (int j = 0; j < trs.size(); j++)
                    {
                        Element tr = trs.get(j);
                        Elements trds = tr.children();
                        int ncounter = 0;
                        for (int i = 0; i < trds.size(); i++)
                        {
                            Element td = trds.get(i);

                            if (td.attr("valign").equals("top"))
                            {
                                if (td.text() != null)
                                    cmap.get(i - ncounter + 1).add(new Course(td.text() + ""));
                                else
                                    cmap.get(i - ncounter + 1).add(new Course(""));
                            } else
                                ncounter++;
                        }
                    }
                    CODE_ERROR = 0;
                    return cmap;
                }
            }

        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CODE_ERROR = 0;
        return null;

    }

    // ��ȡ�γ�
    public List<LessonBean> getLessons(String term)
    {
        try
        {
            URL url = new URL(college_url + "/ZNPK/Private/List_XNXQKC.aspx?xnxq=" + term);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "gbk"));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                builder.append(line);
            }
            String info = builder.toString();

            reader.close();
            conn.disconnect();

            Document doc = Jsoup.parse(info);
            doc = Jsoup.parse(doc.select("script").html().substring(24));
            Elements eles = doc.select("select[name=\"Sel_KC\"] option");
            List<LessonBean> slist = new ArrayList<LessonBean>();
            if (lessonMap != null)
            {
                lessonMap.clear();
            }
            for (Element element : eles)
            {
                String t = " {\"id\":" + element.val() + ",\"name\":" + element.html() + "}";
                LessonBean lesssonBean = new LessonBean(element.val(), element.html());
                slist.add(lesssonBean);
                lessonMap.put(element.val(), lesssonBean);
                System.out.println(t);
            }

            return slist;

        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object get(String sid, String id, String code)
    {

        return null;
    }

}
